package org.zhxy.zhxy.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.HandlerInterceptor;
import org.zhxy.zhxy.utils.AdminHolder;
import org.zhxy.zhxy.exception.UnauthorizedException;
import org.zhxy.zhxy.utils.UserHolder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截器
 */
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

    /**
     * 拦截请求
     * @param request
     * @param response
     * @param handler
     * @return
     */
    @ResponseBody
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 判断是否需要拦截（ThreadLocal中是否有用户）
        String method = request.getMethod();
        if ("OPTIONS".equals(method)){
            return true;
        }
        if (AdminHolder.getAdmin() == null && UserHolder.getUser() == null) {
            // 没有用户，需要拦截，设置状态码为401并返回错误信息
            log.warn("请求未授权: {}", request.getRequestURI());
            throw new UnauthorizedException(401, "该token已过期！");
        }
        // 有用户，放行
        return true;
    }
}
















